#include "stdafx.h"
#include "GlobalDefManager.h"
#include "MgrBase.h"
bool GlobalDefManager::RegisterDefManger( DefMangerBase* pManager )
{
	int32 iID=pManager->GetReflection().GetClassID();
	std::map<int32,DefMangerBase*>::iterator it=m_mDefManagers.find(iID);
	if(it!=m_mDefManagers.end()) return false;
	m_mDefManagers[iID]=pManager;
	return true;
}

DefMangerBase* GlobalDefManager::LookupDefManager( int32 iGroup,int32 iSubID )
{
	int32 iID=MakeClassID(iGroup,iSubID);
	std::map<int32,DefMangerBase*>::iterator it=m_mDefManagers.find(iID);
	if(it==m_mDefManagers.end()) return NULL;
	return it->second;
}
DefMangerBase* GlobalDefManager::LookupDefManager( int32 iID)
{
	std::map<int32,DefMangerBase*>::iterator it=m_mDefManagers.find(iID);
	if(it==m_mDefManagers.end()) return NULL;
	return it->second;
}


void GlobalDefManager::ReadFromArchieves()
{
	std::cout<<"GlobalDefManager::ReadFromArchieves() begin"<<std::endl;
	do 
	{
		std::map<int32,DefMangerBase*>::iterator it= m_mDefManagers.begin();
		int32 ii=1;
		int32 iCount=m_mDefManagers.size();
		for(;it!=m_mDefManagers.end();it++)
		{
			
			DefMangerBase* pManager=it->second;
			std::cout<<"Loading...("<<ii<<"/"<<iCount<<") "<<pManager->GetFilePath()<<"......";
			if(!pManager->ReadFromArchieves())
			{
				printf("Load From File %s  Failed!!!\r\n",pManager->GetFilePath());
			}
			std::cout<<"OK!"<<std::endl;
			ii++;
		}

	} while (false);

	UpdateReference();

	std::cout<<"GlobalDefManager::ReadFromArchieves() end"<<std::endl;

}
void GlobalDefManager::UpdateReference()
{
	do
	{
		std::map<int32,DefMangerBase*>::iterator it= m_mDefManagers.begin();
		for(;it!=m_mDefManagers.end();it++)
		{
			it->second->OnArchieveReaded();
		}

	}while(false);
}
void GlobalDefManager::WirteToArchieves()
{
	std::map<int32,DefMangerBase*>::iterator it= m_mDefManagers.begin();

	for(;it!=m_mDefManagers.end();it++)
	{
		DefMangerBase* pManager=it->second;
		if(!pManager->WriteToArchieves())
		{
			printf("Write to  File %s  Failed!!!\r\n",pManager->GetFilePath());
		}
	}
}

void GlobalDefManager::EnumerateDefManagers( std::vector<DefMangerBase*>& vManagers )
{
	vManagers.clear();
	std::map<int32,DefMangerBase*>::iterator it= m_mDefManagers.begin();

	for(;it!=m_mDefManagers.end();it++)
	{
		DefMangerBase* pManager=it->second;
		vManagers.push_back(pManager);
	}
}

void GlobalDefManager::Release()
{
	std::map<int32,DefMangerBase*>::iterator it= m_mDefManagers.begin();

	for(;it!=m_mDefManagers.end();it++)
	{
		DefMangerBase* pManager=it->second;
		pManager->Release();
	}
}